<?php

namespace app\admin\controller;

use app\BaseController;
use frame\lib\Db;
use PDO;
use PDOException;

class Login extends BaseController
{
    public function index()
    {
        $this->view();
    }
    public function doLog()
    {
        $username = @$_POST['username'];
        $password = @$_POST['password'];
        $code = @$_POST['code'];
        if (empty($username) || empty($password) || empty($code)) error('缺少参数', 201);
        if (!captcha_check($code)) error('验证码错误');
        $data = Db::name('user')->where(['username' => $username, 'role' => '0'])->find();
        if (!$data) error('找不到对应管理员的数据');
        if (md5($password . config('secure', 'secure_salt')) != $data['password']) error('账号或密码错误');
        if ($data['status'] == 2) error('该账户已被封禁');
        $cook = ['username' => $username, 'id' => $data['id']];
        $_SESSION['admin'] = $cook;
        Db::name('user')->where(['id' => $data['id']])->update(['last_login_time' => getTime()]);
        // 登录时间保留7天
        setcookie(session_name(), session_id(), time()+3600 * 24 * 7, '/');
        $this->init(0);
        success();
    }
    public function logOut() {
        if(@$_SESSION['admin'])
        {
            $_SESSION['admin'] = null;
            unset($_SESSION['admin']);
            exit("<script>alert('退出成功');location.href='?p=admin&c=login&a=index';</script>");
        }
    }
      // 初始化配置 
      public function init($user_id)
      {
          $conf = Db::name('config')->where(['user_id' => 0])->find();
          $heat = Db::name('statistics')->where(['user_id' => 0])->find();
          if (empty($conf)) {
              try {
                  $conf['new'] = '还没有添加公告哦！';
                  $conf['is_log'] = 1;
                  $conf['is_reg'] = 1;
                  $conf['is_sign'] = 1;
                  $conf['site'] = 1;
                  // 反馈
                  $conf['feedback'] = 1;
                  // 登录送的积分
                  $conf['log_send_score'] = 0;
                  // 注册送积分
                  $conf['reg_send_score'] = 0;
                  // 注册送会员
                  $conf['reg_vip_time'] = 0;
                  $conf['sign_three'] = 10;
                  $conf['sign_seven'] = 20;
                  $conf['sign_fifteen'] = 30;
                  $data = ['user_id' => 0, 'conf' => json_encode($conf, JSON_UNESCAPED_UNICODE)];
                  Db::name('config')->insert($data);
              } catch (PDOException $e) {
                  error('初始化失败，请重新发送请求 !');
              }
          }
          if(empty($heat))
          {
              try {
                  Db::name('statistics')->insert(['user_id' => 0]);
              } catch (PDOException $e) {
                  error('初始化失败，请重新发送请求 !');
              }
          }
      }
}
